package Util;

import Dto.SerializableDTO;

import java.io.*;

public class OutputAndInputFile {

    private final String FILE_NAME = "yetTryUnlockPassword.txt";

    public void tryOutFile(Object obj) throws IOException {
        if(obj instanceof SerializableDTO) {
            SerializableDTO out = (SerializableDTO) obj;
            //构造一个对象输出流oos
            ObjectOutputStream oos = null;
            //构造一个文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME);
            try {
                //构造对象输出流
                oos = new ObjectOutputStream(fileOutputStream);
                //序列化一个对象到文件变成二进制内容
                oos.writeObject(out);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                assert oos != null;
                fileOutputStream.close();
                oos.close();
            }
        }
    }

    public Object tryReadFile() throws ClassNotFoundException, IOException {
        Object obj = null;
        FileInputStream fis = new FileInputStream(FILE_NAME);
        ObjectInputStream ois = new ObjectInputStream(fis);
        try {
            obj = ois.readObject();
            return obj;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            fis.close();
            ois.close();
        }
    }

}
